import { computed, unref} from 'vue'
import { Columms, ObjTarget } from './types/column'

/**
 * 数据处理
 * @params columns: 遍历的数组
 * @params obj: 处理后的结果
 * @params deep: 当前深度
 * @params isFirst: 是否是第一次调用函数
 * @params currentKey: 从父级到当前子级的key
 * @params fixed: 固定列子集添加fixed值
 */
function getColumnList(columns: Array<Columms>, obj: ObjTarget, deep: number, isFirst: boolean, currentKey: string, fixed: string | undefined) {
  columns.forEach(item => {
    // 重置深度
    if (isFirst) {
      deep = 1
    }
    const ob: Columms = {
      ...item
    }
    ob.keysStr = isFirst ? ob.key : currentKey + '-' + ob.key
    ob.deep = deep
    if (fixed) {
      ob.fixed = fixed
    }
    if (!ob.children) {
      ob.hasChildren = false
      obj.list.push(ob)
    } else {
      ob.hasChildren = true
      deep++
      if (deep > obj.maxDeep) {
        obj.maxDeep = deep
      }
      obj.list.push({
        ...ob,
        children: []
      })
      getColumnList(item.children, obj, deep, false, ob.keysStr, ob.fixed || undefined)
    }
  })
}

export function useColumns(columns: any) {
  const columnObj = computed(() => {
    const obj: any = {
      list: [], // 扁平化数据列表
      maxDeep: 1 // 最大深度
    }
    getColumnList(columns, obj, 1, true, '', undefined)
    obj.list.forEach((item: any) => {
      item.colSpan = obj.list.filter((ite: any) => ite.keysStr.includes(item.key) && !ite.hasChildren).length
      if (!item.hasChildren) {
        item.rowSpan = obj.maxDeep - item.deep + 1 // 根据表格得出规律
      } else {
        item.rowSpan = 1
      }
    })
    return obj
  })
  return unref(columnObj)
}
